<template>
  <div class="box box-body">
    <div v-if="searchbar">
      <el-input v-model="filterText"
                placeholder="模糊搜索" size="small" style="max-width: 360px;"
                prefix-icon="fa fa-search" clearable></el-input>
    </div>
    <el-tree ref="tree" node-key="id" :data="list" :default-checked-keys="value"
             :filter-node-method="filterNode" @check="onNodeClick"
             accordion show-checkbox check-on-click-node default-expand-all
             :expand-on-click-node="false">
    </el-tree>
  </div>
</template>

<script>
/* eslint-disable */
import Layers from "@/lang/layers";
import Bamboo from "@/lang/bamboo";

/**
 * 树形选择器
 */
export default {
    name: 'SeaCheckTree'
    , components: {}

    , props: {
        value: {type: [String, Array], default: Layers.array}
        // 数据字典
        , options: {type: Array, default: Layers.array}
        // 文字提示
        , placeholder: {type: String, default: ''}
        // 搜索栏
        , searchbar: {type: Boolean, default: false}
    }, model: {
        //需要定义哪一个props可以用v-model绑定属性
        prop: 'value',
        //声明一个事件，调用之后，就会改变父级容器的值
        event: 'handlerValueChange'
    }, data() {
        return {
            // 值模型，任何时候都不允许为空，避免VUE联动失效
            valueModel: undefined
            // 组件配置
            , input: undefined
            // 属性数据列表
            , list: undefined
            // 过滤数值
            , filterText: ''
            // 展示搜索栏
            , showSearchbar: false
        }
    }, watch: {
        value: {
            handler: function (val) {
                if (val !== this.valueModel) {
                    this.$refs.tree.setCheckedKeys(val);
                    this.valueModel = val;
                }
            }
        }
        , options: {
            handler: function (val) {
                this.setOptions(val);
            }
            , immediate: true
        }
        /**
         * 数据过滤
         */
        , filterText(val) {
            this.$refs.tree.filter(val);
        }
    }, methods: {
        /**
         * 过滤数据
         */
        filterNode: function (value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        /**
         * 值改变事件
         */
        onChange: function (val) {
            this.$emit('handlerValueChange', val);
            this.$emit('change', val);
        }
        /**
         * 设置新的值
         */
        , setOptions: function (val) {
            this.list = Bamboo.isTree(val) ? val : Bamboo.toTree(val);
        }
        /**
         * 节点点击事件
         * @param node
         */
        , onNodeClick(node) {
            let nodes = this.$refs.tree.getCheckedNodes();
            this.onChange(Bamboo.getIds(nodes));
        }
    }
};
</script>
